<template>
  <div class="role-container">
    <el-card class="role-card">
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <div class="header-buttons">
            <el-button type="primary" @click="showAddDialog">添加角色</el-button>
          </div>
        </div>
      </template>

      <!-- 查询表单 -->
      <el-form :model="queryForm" inline class="query-form">
        <el-form-item label="角色编号">
          <el-input v-model="queryForm.name" placeholder="请输入角色编号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="roles" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色编号" width="120" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="primary" link @click="showEditDialog(row)">编辑</el-button>
            <el-button type="primary" link @click="showPermissionDialog(row)">权限</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑角色对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑角色' : '添加角色'" width="500px">
      <el-form :model="roleForm" label-width="80px">
        <el-form-item label="角色编号">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="roleForm.description" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="权限设置"
      width="500px"
      @opened="handlePermissionDialogOpened"
    >
      <el-tree
        ref="permissionTree"
        :data="permissions"
        show-checkbox
        node-key="id"
        :props="{
          label: 'name',
          children: 'children',
        }"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePermissionSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

interface Role {
  id: number
  name: string
  description: string
}

interface Permission {
  id: number
  name: string
  description: string
  page: string
  action: string
}

interface QueryForm {
  name: string
}

const roles = ref<Role[]>([])
const permissions = ref<Permission[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const isEdit = ref(false)
const currentRole = ref<Role | null>(null)
const permissionTree = ref()

const queryForm = reactive<QueryForm>({
  name: '',
})

const roleForm = ref({
  name: '',
  description: '',
})

// 获取角色列表
const fetchRoles = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value - 1,
      size: pageSize.value,
      name: queryForm.name || undefined,
    }

    const response = await axios.get('/api/roles', { params })
    // 检查返回数据结构
    if (response.data.content) {
      roles.value = response.data.content
      total.value = response.data.totalElements
    } else {
      // 如果返回的不是分页数据，则直接使用返回的数据
      roles.value = response.data
      total.value = response.data.length
    }
  } catch (error) {
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 获取权限列表
const fetchPermissions = async () => {
  try {
    const response = await axios.get('/api/permissions')
    // 将权限按页面分组
    const groupedPermissions = response.data.reduce((acc: any, permission: Permission) => {
      const page = permission.page
      if (!acc[page]) {
        acc[page] = {
          id: `page-${page}`,
          name: page,
          children: [],
        }
      }
      acc[page].children.push({
        id: permission.id,
        name: permission.description,
      })
      return acc
    }, {})

    permissions.value = Object.values(groupedPermissions)
  } catch (error) {
    ElMessage.error('获取权限列表失败')
  }
}

// 显示添加角色对话框
const showAddDialog = () => {
  isEdit.value = false
  roleForm.value = {
    name: '',
    description: '',
  }
  dialogVisible.value = true
}

// 显示编辑角色对话框
const showEditDialog = (role: Role) => {
  isEdit.value = true
  currentRole.value = role
  roleForm.value = {
    name: role.name,
    description: role.description,
  }
  dialogVisible.value = true
}

// 显示权限设置对话框
const showPermissionDialog = async (role: Role) => {
  currentRole.value = role
  permissionDialogVisible.value = true
}

// 处理权限对话框打开事件
const handlePermissionDialogOpened = async () => {
  if (!currentRole.value) return
  try {
    const response = await axios.get(`/api/roles/${currentRole.value.id}/permissions`)
    const permissionIds = response.data.map((p: Permission) => p.id)
    if (permissionTree.value) {
      permissionTree.value.setCheckedKeys(permissionIds)
    }
  } catch (error: any) {
    console.error('获取角色权限失败:', error)
    if (error.response) {
      console.error('错误状态码:', error.response.status)
      console.error('错误信息:', error.response.data)
      ElMessage.error(`获取角色权限失败: ${error.response.data.message || error.response.status}`)
    } else {
      ElMessage.error('获取角色权限失败: ' + (error.message || '未知错误'))
    }
  }
}

// 提交角色表单
const handleSubmit = async () => {
  try {
    if (isEdit.value && currentRole.value) {
      await axios.put(`/api/roles/${currentRole.value.id}`, roleForm.value)
      // 记录更新日志
      await axios.post('/api/logs', {
        action: 'UPDATE_ROLE',
        description: `更新角色：${roleForm.value.name}`,
      })
      ElMessage.success('更新角色成功')
    } else {
      await axios.post('/api/roles', roleForm.value)
      // 记录创建日志
      await axios.post('/api/logs', {
        action: 'CREATE_ROLE',
        description: `创建角色：${roleForm.value.name}`,
      })
      ElMessage.success('添加角色成功')
    }
    dialogVisible.value = false
    fetchRoles()
  } catch (error: any) {
    ElMessage.error(error.response.data.message)
  }
}

// 提交权限设置
const handlePermissionSubmit = async () => {
  if (!currentRole.value) return
  try {
    const checkedKeys = permissionTree.value.getCheckedKeys()
    // 过滤掉页面节点的ID，只保留叶子节点的ID
    const permissionIds = checkedKeys.filter(
      (key: string | number) => typeof key === 'number' || !key.toString().startsWith('page-'),
    )
    await axios.put(`/api/roles/${currentRole.value.id}/permissions`, permissionIds)
    // 记录权限更新日志
    await axios.post('/api/logs', {
      action: 'UPDATE_ROLE_PERMISSIONS',
      description: `更新角色权限：${currentRole.value.name}`,
    })
    ElMessage.success('更新权限成功')
    permissionDialogVisible.value = false
  } catch (error: any) {
    console.error('更新权限失败:', error)
    if (error.response) {
      console.error('错误状态码:', error.response.status)
      console.error('错误信息:', error.response.data)
      ElMessage.error(`更新权限失败: ${error.response.data.message || error.response.status}`)
    } else {
      ElMessage.error('更新权限失败: ' + (error.message || '未知错误'))
    }
  }
}

// 删除角色
const handleDelete = (role: Role) => {
  ElMessageBox.confirm('确定要删除该角色吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await axios.delete(`/api/roles/${role.id}`)
      // 记录删除日志
      await axios.post('/api/logs', {
        action: 'DELETE_ROLE',
        description: `删除角色：${role.name}`,
      })
      ElMessage.success('删除角色成功')
      fetchRoles()
    } catch (error) {
      ElMessage.error('删除角色失败')
    }
  })
}

// 查询
const handleQuery = () => {
  currentPage.value = 1
  fetchRoles()
}

// 重置查询
const resetQuery = () => {
  queryForm.name = ''
  handleQuery()
}

// 处理页码变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchRoles()
}

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchRoles()
}

// 记录页面访问日志
const recordPageAccess = async () => {
  try {
    await axios.post('/api/logs', {
      action: 'ACCESS_PAGE',
      description: '访问角色管理页面',
    })
  } catch (error) {
    console.error('记录页面访问日志失败:', error)
  }
}

// 初始化
onMounted(() => {
  fetchRoles()
  fetchPermissions()
  recordPageAccess()
})
</script>

<style scoped>
.role-container {
  padding: 20px;
}

.role-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.query-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
